<template>
  <div class="upload">
    <van-popup v-model="showUpload" :style="{ height: '100%', width: '100%' }" >
      <van-nav-bar
        @click-left="showUpload = false"
        title="我的头像"
        right-text="保存"
        @click-right="save"
      >
        <template #left>
          <i class="iconfont icon-sdf" style="fontSize: 18px"></i>
        </template>
      </van-nav-bar>
      <div class="avatar">
        <van-uploader
          :after-read="afterRead"
          preview-size="200px"
          v-model="fileList"
          :max-count="1"
          @click-preview="perview"
        >
        </van-uploader>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { ImagePreview } from 'vant'
import { uploadAvatar } from '@/api/api.js'
export default {
  props: ['userInfo'],
  data () {
    return {
      showUpload: false,
      avatar: '',
      fileList: [],
      imgurl: ''
    }
  },
  mounted () {
    this.fileList.push({ url: this.userInfo.avatar })
  },
  methods: {
    afterRead (file) {
      this.imgurl = file.file
    },
    async save () {
      const res = await uploadAvatar(this.imgurl)
      console.log(res)
      this.$emit('editAvatar', res.data.data[0].id)
      this.$toast.success('修改成功')
      this.showUpload = false
    },
    perview () {
      var reader = new FileReader()
      reader.readAsDataURL(this.imgurl)
      reader.addEventListener('load', () => {
        var path = reader.result
        // van中预览图片的组件
        ImagePreview({
          images: [path]
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.upload {
  .avatar {
    text-align: center;
    margin-top: 10px;
    .van-uploader {
      border-radius: 20px;
      /deep/.van-image__error {
        border-radius: 10px;
      }
    }
    .img {
      width: 200px;
      height: 200px;
    }
  }
  /deep/.van-nav-bar__text {
    color: #000;
  }
}
</style>
